
// 用blob的方式下载
function downloadFile (content, url, fileName) {
  const body = document.body || document.documentElement
  const aLink = document.createElement('a')
  aLink.style.display = 'none'
  let filename = fileName || ''
  if (!filename) {
    const urlArr = url.split('/')
    filename = urlArr[urlArr.length - 1]
  }
  aLink.setAttribute('download', filename)
  const blob = new Blob([content])
  aLink.href = URL.createObjectURL(blob)
  body.appendChild(aLink)
  aLink.click()
  body.removeChild(aLink)
}

export function download (url, fileName, cb) {
  const xhr = new XMLHttpRequest()
  xhr.open('GET', url, true)
  xhr.responseType = 'blob'
  xhr.onload = function () {
    if (xhr.readyState !== 4) { return }
    if (xhr.status === 200) {
      downloadFile(xhr.response, url, fileName)
      cb && cb()
      return
    }
    cb && cb()
  }
  xhr.send()
}
